package de.digisalt.dsnesds.editors.projectmeta.operations;

import java.util.HashSet;
import java.util.Iterator;

import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.operations.IUndoContext;
import org.eclipse.core.commands.operations.IUndoableOperation;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;

import de.digisalt.dsnesds.editors.projectmeta.model.Model;

public class AbstractUndoableOperation
{
		private final String								msg;
		private final int										newValue;
		private final Model									model;
		private final int										previousVersion;
		private final HashSet<IUndoContext>	undoContexts	= new HashSet<IUndoContext>();

		public ChangeGameVersionOperation(String msg, Model model, int newValue)
		{
			this.msg = msg;
			this.model = model;
			this.newValue = newValue;
			this.previousVersion = model.getVersion();
		}

		@Override
		public void addContext(IUndoContext context)
		{
			this.undoContexts.add(context);
		}

		@Override
		public boolean canExecute()
		{
			return true;
		}

		@Override
		public boolean canRedo()
		{
			return true;
		}

		@Override
		public boolean canUndo()
		{
			return true;
		}

		@Override
		public void dispose()
		{
			// TODO Auto-generated method stub

		}

		@Override
		public IStatus execute(IProgressMonitor monitor, IAdaptable info)
				throws ExecutionException
		{
			model.setVersion(newValue);
			return Status.OK_STATUS;
		}

		@Override
		public IUndoContext[] getContexts()
		{
			int s = undoContexts.size();
			IUndoContext[] contexts = new IUndoContext[s];
			Iterator<IUndoContext> iterator = undoContexts.iterator();
			for (int i = 0; i < s; i++)
			{
				contexts[i] = iterator.next();
			}
			return contexts;
		}

		@Override
		public String getLabel()
		{
			return msg;
		}

		@Override
		public boolean hasContext(IUndoContext context)
		{
			if (undoContexts.size() > 0)
			{
				return true;
			}
			return false;
		}

		@Override
		public IStatus redo(IProgressMonitor monitor, IAdaptable info)
				throws ExecutionException
		{
			model.setVersion(newValue);
			return Status.OK_STATUS;
		}

		@Override
		public void removeContext(IUndoContext context)
		{
			// TODO Auto-generated method stub

		}

		@Override
		public IStatus undo(IProgressMonitor monitor, IAdaptable info)
				throws ExecutionException
		{
			model.setVersion(previousVersion);
			return Status.OK_STATUS;
		}

}
